package util;

import domain.User;
import mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.List;

public class DynanicSqlTest {

    private static SqlSession session = null;
    private static UserMapper mapper = null;

    static {
        try {
            session = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("sqlMapConfig.xml")).openSession();
            mapper = session.getMapper(UserMapper.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
    * 测试动态SQL : if
    * 排除null和‘’的情况
    * <if test="address != null and address.trim() != ''">
    *   and address #{address}
    * </if>
    * */
    @Test
    public void testIf(){
        QueryEntity condition = new QueryEntity();
        condition.setId(null);
        condition.setAddress("北京金燕龙");
        condition.setSex(" ");
        List<User> users = mapper.findByMultiCondition(condition);
        users.forEach(System.out::println);
    }

    /*
    * choose、when、otherwise
    * 传入username就按username查找，传入sex就按sex查找，若两者都没传，就返回标记为featured的user·
    * */
    @Test
    public void testChoose(){
        QueryEntity queryEntity = new QueryEntity();
        queryEntity.setUsername("老王");
        List<User> users = mapper.queryActiveLike(queryEntity);
        users.forEach(System.out::println);
    }

    /**
     *  where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。
     *  而且，若子句的开头为 “AND” 或 “OR”，where 元素也会将它们去除。
     */
    @Test
    public void testWhere(){
        QueryEntity queryEntity = new QueryEntity();
        //queryEntity.setId(41);
        queryEntity.setUsername("老王");
        List<User> users = mapper.findByWhere(queryEntity);
        users.forEach(System.out::println);
    }

    /**
     * 测试动态SQL trim where
     */
    @Test
    public void testTrim(){
        QueryEntity queryEntity = new QueryEntity();
        queryEntity.setUsername("老王");
        List<User> users = mapper.findByTrimWhere(queryEntity);
        users.forEach(System.out::println);
    }


}
